package mainUI;


import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.helper.ExitAppUtil;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.utils.AndroidUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.rey.material.app.ThemeManager;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemClickListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLEncoder;

import application.AppApplication;
import application.HttpUrlConstant;
import application.KeyConstant;
import frame.UIFragment;
import interfaces.IReturnObject;
import interfaces.ISignalrListener;
import menhoo.com.i8officelibrary.R;
import model.LoginUser;
import model.TabModel;
import receiver.SignalrReceiver;
import service.SignalrService;

/**
 * Created by yanglei on 15/9/17.
 */
public abstract class AppFragment extends UIFragment {
    protected BackHandledInterface mBackHandledInterface;

    public interface BackHandledInterface {
        public abstract void setSelectedFragment(AppFragment selectedFragment);
    }

    /**
     * 是否显示TitleBar
     */
    public boolean IsShowTitle = true;
    /**
     * 是否显示返回按钮
     */
    public boolean IsShowBtnBack = true;
    /**
     * 关闭的时候是否可以返回结果
     */
    public boolean IsReturnResult = false;

    /**
     * 可用来传递对象
     */
    public Bundle TagBundle = null;


    private String Title = "";
    //
    private SignalrReceiver signalrReceiver;
    private ISignalrListener iSignalrListener;
    private boolean isRunSignalrService = false;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!(getActivity() instanceof BackHandledInterface)) {
            throw new ClassCastException("Hosting Activity must implement BackHandledInterface");
        } else {
            this.mBackHandledInterface = (BackHandledInterface) getActivity();
        }

        try {
            IsShowTitle = getArguments().getBoolean("IsShowTitle");
        } catch (Exception e) {//LogUtils.e(e.getMessage() + "");
        }
        try {
            IsShowBtnBack = getArguments().getBoolean("IsShowBtnBack");
        } catch (Exception e) {//LogUtils.e(e.getMessage() + "");
        }
        try {
            IsReturnResult = getArguments().getBoolean("IsReturnResult");
        } catch (Exception e) {//LogUtils.e(e.getMessage() + "");
        }
        try {
            Title = getArguments().getString("Title");
        } catch (Exception e) {//LogUtils.e(e.getMessage() + "");
        }
        try {
            TagBundle = getArguments().getBundle("TagBundle");
        } catch (Exception e) {//LogUtils.e(e.getMessage() + "");
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //告诉FragmentActivity，当前Fragment在栈顶
        mBackHandledInterface.setSelectedFragment(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isRunSignalrService) {
            //
            signalrReceiver = new SignalrReceiver() {
                @Override
                public void SignalrHandle(Context context, Intent intent, String action, String data) {
                    if (iSignalrListener != null) {
                        JSONObject jsonData = null;
                        try {
                            jsonData = new JSONObject(data);
                        } catch (Exception ex) {
                        }
                        switch (action) {
                            case "onStart":
                                iSignalrListener.OnStart(context, intent, data);
                                break;
                            case "onStop":
                                iSignalrListener.OnStop(context, intent);
                                break;
                            case "onRefreshOnline":
                                iSignalrListener.OnRefreshOnline(context, intent, data);
                                break;
                            case "hasUserOnline":
                                iSignalrListener.HasUserOnline(context, intent, jsonData);
                                break;
                            case "hasUserOffline":
                                iSignalrListener.HasUserOffline(context, intent, jsonData);
                                break;
                            case "onMessage":
                                iSignalrListener.OnMessage(context, intent, jsonData);
                                break;
                            case "hasCvnUpdate":
                                iSignalrListener.HasCvnUpdate(context, intent, jsonData);
                                break;
                        }
                    }
                }
            };

            //注册
            context.registerReceiver(signalrReceiver, new IntentFilter(signalrReceiver.Action));
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //解除
        if (signalrReceiver != null) {
            context.unregisterReceiver(signalrReceiver);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    public String getTitle() {
        return Title;
    }

    @Override
    public void init() {
        super.init();
        setTitleDisplay(IsShowTitle);
        setBtnBackDisplay(IsShowBtnBack);
        setTitle(Title);

    }

    /**
     * 显示一个简单的提示框
     *
     * @param message      提示文字
     * @param isCancelable 是否是模式弹出(点击周边是否会消失)
     */
    public void showSimpleDialogMessage(String message, boolean isCancelable) {
        showSimpleDialogMessage(message, null, null, isCancelable, false);
    }

    public void showSimpleDialogMessage(String message, final IReturnObject positiveAction, boolean isCancelable, boolean isCancelBtn) {
        showSimpleDialogMessage(message, positiveAction, null, isCancelable, isCancelBtn);
    }

    /**
     * 显示一个简单的提示框
     *
     * @param message        提示文字
     * @param positiveAction 点击确定按钮之后的回调函数
     * @param isCancelable   是否是模式弹出(点击周边是否会消失)
     * @param isCancelBtn    是否显示取消按钮
     */
    public void showSimpleDialogMessage(String message, final IReturnObject positiveAction, final IReturnObject neutralAction, boolean isCancelable, boolean isCancelBtn) {
        StringBuilder sb = new StringBuilder();
        if (message.length() < 40) {
            int _len = (40 - message.length()) / 2;

            for (int i = 0; i < _len; i++) {
                sb.append(" ");
            }
            sb.append(message);
            for (int i = 0; i < _len; i++) {
                sb.append(" ");
            }
        } else {
            sb.append(message);
        }

        boolean isLightTheme = ThemeManager.getInstance().getCurrentTheme() == 0;
        Dialog.Builder builder = new SimpleDialog.Builder(isLightTheme ? R.style.SimpleDialogLight : R.style.SimpleDialog) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                if (positiveAction != null)
                    positiveAction.returnResult(null);
            }

            @Override
            public void onNeutralActionClicked(DialogFragment fragment) {
                if (neutralAction != null)
                    neutralAction.returnResult(null);
                fragment.dismiss();
            }
        };

        ((SimpleDialog.Builder) builder).message(sb.toString())
                .positiveAction("确定");
        if (isCancelBtn) {
            builder.neutralAction("取消");
        }

        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.setCancelable(isCancelable);
        fragment.show(getFragmentManager(), null);
    }

    public AppActivity getAppActivity() {
        return ((AppActivity) getActivity());
    }

    public void setOnMenuItemClickListener(OnMenuItemClickListener onMenuItemClickListener) {
        getAppActivity().setOnMenuItemClickListener(onMenuItemClickListener);
    }

    /**
     * 检查是否已经登陆过了,如果没有则重新登陆,再执行传递过来的参数
     *
     * @param returnObject
     */
    public void checkLogin(IReturnObject<Boolean> returnObject) {
        if (!Check.isEmpty(AppApplication.getSession())) {
            returnObject.returnResult(true);
        } else {
            //重新登陆
            LoginUser user = AppApplication.getUser();
            try {
                //设置网站默认地址
                HttpUrlConstant.setWebSite(AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppIPUrl));
            } catch (Exception e) {
                LogUtils.e(e.getMessage() + "");
            }

            if (user != null) {
                Login(user.userName, user.pwd, returnObject);
            }
        }

    }


    /**
     * 登陆
     *
     * @param name
     * @param pwd
     * @param returnObject
     */
    public void Login(final String name, final String pwd, final IReturnObject<Boolean> returnObject) {
        Login(name, pwd, returnObject, true);
    }

    /**
     * 登陆
     *
     * @param name
     * @param pwd
     * @param returnObject
     * @param isShowLoading
     */
    public void Login(final String name, final String pwd, final IReturnObject<Boolean> returnObject, boolean isShowLoading) {

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("name", name);
        params.addQueryStringParameter("pwd", pwd);

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Type", "MobileApp");
            jsonObject.put("Hardware", AndroidUtil.getUniqueID(context));
            jsonObject.put("Info", "android");
            params.addQueryStringParameter("device", jsonObject.toString());
        } catch (Exception ex) {
        }

        params.addQueryStringParameter("persistent", "true");
        httpHelp(HttpMethod.POST, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.Login), params, new RequestCallBack() {

            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                if (responseInfo.result != null) {
                    //登陆成功
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result.toString());
                        if (jsonObject.getBoolean("Succeed")) {

                            AppApplication.setSession(jsonObject.getString("Message"));
                            JSONObject jsonData = jsonObject.getJSONObject("Data");
                            JSONArray NavbarArray = jsonData.isNull("Navbar") ? null : jsonData.getJSONArray("Navbar");

                            LoginUser user = new LoginUser();
                            user.userName = name;
                            user.pwd = pwd;
                            user.EmplID = jsonData.getString("ID");
                            user.EmplName = jsonData.getString("Name");
                            user.ProductID = jsonData.getString("ProductID");
                            user.ProductName = jsonData.getString("ProductName");
                            user.DeptAndPos = jsonData.getString("DeptAndPos");
                            user.Image = jsonData.getString("Image");
                            user.CanInvite = jsonData.getBoolean("CanInvite");
                            user.InvitePhoneUrl = jsonData.getString("InvitePhoneUrl");
                            user.InviteWechatUrl = jsonData.getString("InviteWechatUrl");

                            if (AppApplication.getUser() != null) {
                                user.setId(AppApplication.getUser().getId());
                                user.autoLogin = AppApplication.getUser().autoLogin;

                                getDB().deleteAll(LoginUser.class);
                                getDB().save(user);
                            } else {
                                getDB().save(user);
                            }

                            AppApplication.setUser(getDB().findFirst(LoginUser.class));
                            //保存导航Navbar
//                            if (NavbarArray != null && NavbarArray.length() > 0) {
//                                //先清空数据库
//                                getDB().deleteAll(TabModel.class);
//                                for (int i = 0; i < NavbarArray.length(); i++) {
//                                    JSONObject navber = NavbarArray.getJSONObject(i);
//                                    String Code = navber.getString("Code");
//                                    String Name = navber.getString("Name");
//                                    String Type = navber.getString("Type");
//                                    String Permisson = navber.isNull("Permisson") ? "" : navber.getString("Permisson");
//                                    String Icon = navber.getString("Icon");
//                                    String Url = navber.getString("Url");
//
//                                    TabModel model = new TabModel();
//                                    model.code = Code;
//                                    model.type = Type;
//                                    model.name = Name;
//                                    model.permisson = Permisson;
//                                    model.htmlUrl = Url;
//                                    model.iconUrl = HttpUrlConstant.getWebSiteFullUrl(Icon);
//                                    model.isShow = (Check.isEmpty(Code) || Code.equalsIgnoreCase("NULL")) ? false : true;
//
//                                    //写入数据
//                                    getDB().save(model);
//                                }
//
//                            }
                            //
                            if (AppApplication.getALiYunDeviceId() == null) {
//                                MessageUtil.showLongToast(context, "无法与服务器建立推送连接");
                                //成功
                                if (returnObject != null)
                                    returnObject.returnResult(true);
                            } else {
                                AddDeviceToken(AppApplication.getALiYunDeviceId(), new IReturnObject() {
                                    @Override
                                    public void returnResult(Object result) {
                                        //成功
                                        if (returnObject != null)
                                            returnObject.returnResult(true);
                                    }
                                });
                            }


                        } else {
                            String Message = jsonObject.getString("Message");
                            if (Message.equals("PWD_INVALID")) {
                                MessageUtil.showShortToast(context, "用户名密码错误");
                            } else if (Message.equals("NO_USER")) {
                                MessageUtil.showShortToast(context, "此用户尚未注册");
                            }
                            if (returnObject != null)
                                returnObject.returnResult(false);
                        }

                    } catch (Exception e) {
                        MessageUtil.showShortToast(context, "无法登陆,请联系网站管理员");
                        if (returnObject != null)
                            returnObject.returnResult(false);
                    }
                } else {
                    if (returnObject != null)
                        returnObject.returnResult(false);
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                if (returnObject != null)
                    returnObject.returnResult(false);
            }
        }, isShowLoading);

    }

    /*
    向服务器注册 TokenID
     */
    public void AddDeviceToken(String aliyunDeviceId, final IReturnObject returnObject) {
        String deviceName = "Android:" + Build.VERSION.RELEASE + "(" + Build.VERSION.SDK + ")"; //"Android:"+Build.VERSION.RELEASE+"("+Build.VERSION.SDK+"),"+ Build.MODEL+","+Build.BRAND;
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        params.addQueryStringParameter("deviceId", aliyunDeviceId);
        params.addQueryStringParameter("appName", getString(R.string.app_name));
        //params.addQueryStringParameter("deviceName", AndroidUtil.printSystemInfo());
        params.addQueryStringParameter("deviceName", URLEncoder.encode(deviceName));

        httpHelp(HttpMethod.GET, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.AddDeviceToken), params, new RequestCallBack
                () {


            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                String result = responseInfo.result == null ? null : responseInfo.result.toString();
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (!jsonObject.getBoolean("Succeed")) {
                            MessageUtil.showShortToast(context, "TokenID 没有成功注册到 web 失败");
                            LogUtils.e("" + jsonObject.getString("Message"));
                        }
                    } catch (Exception e) {
                        LogUtils.e("" + e.getMessage());
                    }
                }
                returnObject.returnResult("成功");
            }

            @Override
            public void onFailure(HttpException e, String s) {
                returnObject.returnResult("失败");
            }
        }, false);

    }

    public void DeleteDeviceToken(String aliyunDeviceId, final IReturnObject returnObject) {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        params.addQueryStringParameter("deviceId", aliyunDeviceId);

        httpHelp(HttpMethod.GET, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.DeleteDeviceToken), params, new RequestCallBack
                () {


            @Override
            public void onSuccess(ResponseInfo responseInfo) {

                String result = responseInfo.result == null ? null : responseInfo.result.toString();
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (!jsonObject.getBoolean("Succeed")) {
                            MessageUtil.showShortToast(context, "TokenID delete失败");
                            LogUtils.e("" + jsonObject.getString("Message"));
                        }
                    } catch (Exception e) {
                        LogUtils.e("" + e.getMessage());
                    }
                }

                //清空session
                AppApplication.setSession(null);
                //取消自动登陆
                try {
                    LoginUser user = AppApplication.getUser();
                    user.autoLogin = false;
                    getDB().update(user);
                    //停止udp推送
                    //getAppActivity().stopUDPPushService();
                    AppApplication.getInstance().clearAlias();

                } catch (Exception ex) {
                    LogUtils.e(ex.getMessage() + "");
                }

                //清空TabModel数据库
                try {
                    getDB().deleteAll(TabModel.class);
                    //网络断开siganalr逻辑代码
                    SignalrService signalr =getAppActivity().getSignalrService();
                    if(signalr!=null){
                        signalr.StopSignalr();
                    }
                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                }
                HandlerUtil.runOnUiThreadDelay(new Runnable() {
                    @Override
                    public void run() {
                        ExitAppUtil.getInstance().exitAllActivity();
                        AppApplication.openLogin(getAppActivity());
                        //startActivity(new Intent(getAppActivity(), Login.class));
                    }
                }, 400);

                returnObject.returnResult("成功");
            }

            @Override
            public void onFailure(HttpException e, String s) {
                returnObject.returnResult("失败:" + s);
            }
        }, false);

    }

    /**
     * session过期对话框
     */
    public void sessionOverdue() {
        loginIdIsOverdue("SESSION_INVALID");
    }

    protected void loginIdIsOverdue(String message) {
        if (message == null) {
            MessageUtil.showShortToast(context, "身份验证有问题,但是没有任何的提示信息");
        } else if (message.indexOf("SESSION_INVALID") >= 0) {
            showSimpleDialogMessage(getString(R.string.login_id_is_overdue), new IReturnObject() {
                @Override
                public void returnResult(Object result) {
                    ExitAppUtil.getInstance().exitAllActivity();
                    AppApplication.openLogin(context);
                    //startActivity(new Intent(context, Login.class));
                }
            }, false, true);
        }
    }

    /**
     * 可以传递参数的Get Http请求 会进行session认证
     *
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param returnObj 成功之后返回的结果字符串
     */
    public void Get(final String url, final RequestParams params, final IReturnObject<String> returnObj) {
        checkLogin(new IReturnObject<Boolean>() {
            @Override
            public void returnResult(Boolean result) {
                if (result) {
                    if (params != null) {
                        params.addQueryStringParameter("__session__", AppApplication.getSession());
                    }
                    final String urlF = HttpUrlConstant.getWebSiteFullUrl(url);
                    httpGet(urlF, params, new IReturnObject<String>() {
                        @Override
                        public void returnResult(String result) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {
                                    returnObj.returnResult(result);
                                } else {
                                    String message = jsonObject.isNull("Message") ? null : jsonObject.getString("Message");
                                    loginIdIsOverdue(message);
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    });
                } else {
                    MessageUtil.showShortToast(context, "登陆-身份-出现问题");
                }
            }
        });

    }

    /**
     * Get Http请求 会进行session认证
     *
     * @param url       url地址
     * @param returnObj 成功之后返回的结果字符串
     */
    public void Get(final String url, final IReturnObject<String> returnObj) {
        checkLogin(new IReturnObject<Boolean>() {
            @Override
            public void returnResult(Boolean result) {
                if (result) {
                    RequestParams params = new RequestParams();
                    params.addQueryStringParameter("__session__", AppApplication.getSession());
                    final String urlF = HttpUrlConstant.getWebSiteFullUrl(url);
                    LogUtils.e("请求所有人---__session__"+AppApplication.getSession());
                    LogUtils.e("请求所有人---urlF"+urlF);
                    httpGet(urlF, params, new IReturnObject<String>() {
                        @Override
                        public void returnResult(String result) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                LogUtils.e("请求所有人---成功"+jsonObject.toString());
                                //LogUtils.e("数据获取成功："+jsonObject.toString());
                                if (jsonObject.getBoolean("Succeed")) {
                                    returnObj.returnResult(result);
                                } else {
                                    String message = jsonObject.isNull("Message") ? null : jsonObject.getString("Message");
                                    loginIdIsOverdue(message);
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    });
                } else {
                    MessageUtil.showShortToast(context, "登陆-身份-出现问题");
                }
            }
        });

    }

    /**
     * 可以传递参数的Post Http请求 会进行session认证
     *
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param returnObj 成功之后返回的结果字符串
     */
    public void Post(final String url, final RequestParams params, final IReturnObject<String> returnObj) {
        checkLogin(new IReturnObject<Boolean>() {
            @Override
            public void returnResult(Boolean result) {
                if (result) {
                    if (params != null) {
                        params.addQueryStringParameter("__session__", AppApplication.getSession());
                    }
                    final String urlF = HttpUrlConstant.getWebSiteFullUrl(url);
                    httpPost(urlF, params, new IReturnObject<String>() {
                        @Override
                        public void returnResult(String result) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {
                                    returnObj.returnResult(result);
                                } else {
                                    String message = jsonObject.isNull("Message") ? null : jsonObject.getString("Message");
                                    loginIdIsOverdue(message);
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    });
                } else {
                    MessageUtil.showShortToast(context, "登陆-身份-出现问题");
                }
            }
        });

    }

    /**
     * Post Http请求 会进行session认证
     *
     * @param url       url地址
     * @param returnObj 成功之后返回的结果字符串
     */
    public void Post(final String url, final IReturnObject<String> returnObj) {
        checkLogin(new IReturnObject<Boolean>() {
            @Override
            public void returnResult(Boolean result) {
                if (result) {
                    RequestParams params = new RequestParams();
                    params.addQueryStringParameter("__session__", AppApplication.getSession());
                    final String urlF = HttpUrlConstant.getWebSiteFullUrl(url);
                    httpPost(urlF, params, new IReturnObject<String>() {
                        @Override
                        public void returnResult(String result) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {
                                    returnObj.returnResult(result);
                                } else {
                                    String message = jsonObject.isNull("Message") ? null : jsonObject.getString("Message");
                                    loginIdIsOverdue(message);
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    });
                } else {
                    MessageUtil.showShortToast(context, "登陆-身份-出现问题");
                }
            }
        });

    }

    /**
     * 设置signalr监控
     *
     * @param iSignalrListener
     */
    public void setSignalreceiverHandle(ISignalrListener iSignalrListener) {
        this.iSignalrListener = iSignalrListener;
    }

    public boolean isRunSignalrService() {
        return isRunSignalrService;
    }

    /**
     * 设置是否运行signalr连接服务，要在super.onCreate(savedInstanceState);之前调用
     *
     * @param runSignalrService
     */
    public void setRunSignalrService(boolean runSignalrService) {
        isRunSignalrService = runSignalrService;
    }
}
